//
//  ConsultViewController.m
//  SHHCPhone
//
//  Created by sheng long on 14-6-29.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "ConsultViewController.h"
#import "ConsultView.h"

@interface ConsultViewController ()
{
    //客服中心聊天View
    ConsultView *chatView;
    
    BOOL isFirst;
    
    //当前消息
    ConsultInfo *currentMsg;
}
@end

@implementation ConsultViewController

@synthesize consultType;
@synthesize saveDataText;

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *text = nil;
    if (consultType == FEEDBACK_TYPE) {
        text = @"意见反馈";
    }else{
        text = @"营养咨询";
    }
    self.saveDataText = [text stringByAppendingString:@"保存数据"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveData:) name:saveDataText object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    for (UIView *view in navigationBarView.subviews) {
        [view removeFromSuperview];
    }
    
    if (consultType == FEEDBACK_TYPE) {
        [navigationBarView setTitle:@"意见反馈"];
        [navigationBarView setNormalLeftButton];
    }else{
        [navigationBarView setTitle:@"营养咨询"];
        [self showNavbarStyle];
    }
}

-(void)showView
{
    [self hideProgressView];
    
    //客服中心聊天View
    chatView = [[ConsultView alloc] initWithFrame:CGRectMake(0, NAVIGATIONBAR_HEIGHT, CURRENT_CONTENT_WIDTH, CURRENT_CONTENT_HEIGHT-NAVIGATIONBAR_HEIGHT) superVC:self];
    [self.view addSubview:chatView];
    [chatView addObserver];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (chatView) {
        [chatView addObserver];
    }
    
    if (!isFirst) {
        isFirst = YES;
        [self againLoading];
    }
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [chatView removeObserver];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [chatView.chatText resignFirstResponder];
}

//重新加载数据
-(void)againLoading
{
    [self showProgressView:nil belowSubview:navigationBarView];
    [self refreshTableData];
}

//发送消息
-(void)sendMsg:(ConsultInfo*)msg
{
    currentMsg = msg;

    [LoadingFrameView showLoadingview];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setValue:APP_USER_MSG.id forKey:@"user_id"];
    [dic setValue:msg.content forKey:@"content"];
    
    ASIHTTPRequest *request = nil;
    if (consultType==KF_TYPE) {
        [dic setValue:IOS_CONSULT forKey:IOS_METHOD_NAME];
        request = [NetUtls httpPost:self withValue:dic tag:IOS_CONSULT_TAG need:NO];
    }else{
        [dic setValue:IOS_FEEDBACK forKey:IOS_METHOD_NAME];
        request = [NetUtls httpPost:self withValue:dic tag:IOS_FEEDBACK_TAG need:NO];
    }
    [self.netArray addObject:request];
    [self superASIStartAsynchronous:request];
}

#pragma mark - 加载数据
//刷新数据
-(void)refreshTableData
{
    [self addData:nil];
}

//加载更多数据
-(void)loadingMoreTableData
{
    if (chatView.mainTable.autoDataArray.count > 0) {
        ConsultInfo *info = (ConsultInfo*)chatView.mainTable.autoDataArray.firstObject;
        if (info.id) {
            [self addData:info.id];
        }else if(chatView.mainTable.autoDataArray.count > 1){
            info = (ConsultInfo*)[chatView.mainTable.autoDataArray objectAtIndex:1];
            [self addData:info.id];
        }else{
            [self addData:nil];
        }
    }else{
        [self addData:nil];
    }
}

-(void)addData:(NSString*)lastid
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setValue:APP_USER_MSG.id forKey:@"user_id"];
    [dic setValue:[NSNumber numberWithInt:IOS_GET_NUMBER] forKey:@"count"];
    if (lastid) {
        [dic setValue:lastid forKey:@"max_id"];
    }
//    [dic setValue:[NSNumber numberWithInt:page] forKey:@"page"];
    
    ASIHTTPRequest *request = nil;
    if (consultType == KF_TYPE) {
        [dic setValue:IOS_MYCONSULTLIST forKey:IOS_METHOD_NAME];
        request = [NetUtls httpGet:self withValue:dic tag:IOS_MYCONSULTLIST_TAG need:NO];
    }else{
        [dic setValue:IOS_MYFEEDBACKLIST forKey:IOS_METHOD_NAME];
        request = [NetUtls httpGet:self withValue:dic tag:IOS_MYFEEDBACKLIST_TAG need:NO];
    }
    
    [self.netArray addObject:request];
    [request startAsynchronous];
}

#pragma mark - ASIHTTPRequestDelegate
-(void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@",[request responseString]);
    NSDictionary *dic = [[request responseString] objectFromJSONString];
    if (dic != nil) {
        if (!chatView) {
            [self showView];
        }
        NSArray *array = [dic objectForKey:@"list"];
        if (array.count == 0) {
            if (chatView.mainTable.autoDataArray.count>0) {
                [LoadingFrameView autoDisappearTipview:@"没有更多数据"];
                [chatView.mainTable recoverShowState];
            }else{
                [chatView.mainTable noMsgRefreshView];
            }
        }else{
            NSMutableArray *oldArray = [NSMutableArray arrayWithArray:chatView.mainTable.autoDataArray];
            if (oldArray.count==0) {
                for (int i =0; i<array.count; i++) {
                    ConsultInfo *info = [[ConsultInfo alloc] init:[array objectAtIndex:i]];
                    if (info.pubtime) {
                        info.pubtime = [z_DateTime encodeTime:[NSDate dateWithTimeIntervalSince1970:[info.pubtime integerValue]]];
                    }
                    [oldArray addObject:info];
                }
            }else{
                for (int i = array.count-1; i>=0 ; i--) {
                    ConsultInfo *info = [[ConsultInfo alloc] init:[array objectAtIndex:i]];
                    if (info.pubtime) {
                        info.pubtime = [z_DateTime encodeTime:[NSDate dateWithTimeIntervalSince1970:[info.pubtime integerValue]]];
                    }
                    [oldArray insertObject:info atIndex:0];
                }
            }
            chatView.mainTable.autoDataArray = oldArray;
        }
    }else{
        [self requestFailed:request];
    }
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
    if (request.tag == IOS_MYCONSULTLIST_TAG || request.tag == IOS_MYFEEDBACKLIST_TAG) {
        if (chatView) {
            [chatView.mainTable recoverShowState];
        }else{
            //是否存在本地数据
            NSString *local = [self getLocalData];
            if (local) {
                [self loadView:local];
            }else{
                [self clickAgainLoadingView:0];
            }
        }
    }else{
        [LoadingFrameView autoDisappearTipview:@"发送消息失败"];
    }
}

//父类获取服务器返回信息，成功获取到数据执行方法
-(void)getASIRecordSucceed:(ASIHTTPRequest *)request data:(NSDictionary*)dic
{
    if ([[dic objectForKey:@"result"] integerValue] == 1) {
        chatView.chatText.text = nil;
        currentMsg.id = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
        [chatView.mainTable addSendMsg:currentMsg];
    }
    
    [LoadingFrameView directlyDisappear];
}

//父类获取服务器返回信息，未成功获取到数据执行方法
-(void)getASIRecordFailed:(ASIHTTPRequest *)request data:(NSString*)failed
{
    [LoadingFrameView autoDisappearBlockingview:failed];
}

#pragma mark - 本地数据处理
-(void)saveData:(NSNotification*)note
{
    NSMutableArray *dArray = [NSMutableArray arrayWithCapacity:1];
    
    NSArray *array = [note.userInfo objectForKey:@"data"];
    for (int i = (array.count-1); i >= 0 ; i--) {
        ConsultInfo *info = [array objectAtIndex:i];
        if ([info.isreply intValue]!=-1) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
            [dic setObject:info.id forKey:@"id"];
            [dic setObject:info.content forKey:@"content"];
            CLog(@"info.user=====%@",info.user);
            if (info.user) {
                [dic setObject:[NSDictionary dictionaryWithDictionary:info.user] forKey:@"user"];
            }
            CLog(@"info.user=====%@",info.isreply);
            if (info.isreply) {
                [dic setObject:info.isreply forKey:@"isReply"];
            }
            [dArray insertObject:dic atIndex:0];
        }
        if (dArray.count == IOS_GET_NUMBER) {
            break;
        }
    }
    CLog(@"navigationBarView.titleText=======%@",navigationBarView.titleText);
    if (dArray.count > 0) {
        [self saveLocalData:[dArray JSONString]];
    }else{
        [self saveLocalData:nil];
    }
}

-(void)loadView:(NSString*)data
{
    if (!chatView) {
        [self showView];
    }
    
    NSArray *array = [data objectFromJSONString];
    
    NSMutableArray *oldArray = [NSMutableArray arrayWithCapacity:1];
    for (int i =0; i<array.count; i++) {
        [oldArray addObject:[[ConsultInfo alloc] init:[array objectAtIndex:i]]];
    }

    chatView.mainTable.autoDataArray = oldArray;
}

@end
